package com.itheima.controller;

import com.itheima.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;
    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        log.info(basePath +"\\"+ name);
        FileInputStream fis = new FileInputStream( new File(basePath +"\\"+ name));
        ServletOutputStream sos = response.getOutputStream();
        response.setContentType("image/jpeg");
        byte[] bytes = new byte[1024];
        int read = 0;
        while (( read = fis.read(bytes)) != -1){
                 sos.write(bytes,0,read);
                 sos.flush();

        }
        sos.close();
        fis.close();

    }


    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info(file.toString());
        String originalFilename = file.getOriginalFilename(); //原始文件名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//根据.截取
        String fileName = UUID.randomUUID().toString() + suffix; //重新生成文件名,防止重复
        //创建一个目录
        File dir = new File(basePath);
        if (!dir.exists()) {
            //不存在，则创建
            dir.mkdirs();
        }

        try {
            File f = new File(basePath  +"\\" + fileName);
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }


}
